//
//  COPresentAnimtaionControllerViewController.swift
//  COmix
//
//  Created by Ruthless on 2023/8/16.
//

import UIKit

class COPresentAnimtaionControllerViewController: UIPresentationController {
    private lazy var dimingView: UIView = {
        let vi = UIView()
        vi.backgroundColor = .rgba(0, 0, 0, 0.25)
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(dimingViewClick(_:)))
        vi.addGestureRecognizer(tap)
        return vi
    }()
    override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
        super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
    }
    
    override func presentationTransitionWillBegin() {
        containerView?.addSubview(self.dimingView)
        dimingView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        dimingView.alpha = 0
        self.presentingViewController.transitionCoordinator?.animate(alongsideTransition: { _ in
            self.dimingView.alpha = 1.0
        }, completion: nil)
    }
    
    override func presentationTransitionDidEnd(_ completed: Bool) {
        if !completed {
            dimingView.removeFromSuperview()
        }
    }
    
    override func dismissalTransitionWillBegin() {
        self.presentingViewController.transitionCoordinator?.animate(alongsideTransition: { _ in
            self.dimingView.alpha = 0
        }, completion: nil)
    }
    
    override func dismissalTransitionDidEnd(_ completed: Bool) {
        if completed {
            dimingView.removeFromSuperview()
        }
    }
    
    override func containerViewWillLayoutSubviews() {
        super.containerViewWillLayoutSubviews()
        if let coor = self.presentingViewController.transitionCoordinator {
            if coor.transitionDuration <= 0 {
                adjustPresentedView()
            }
        }
    }
    
    @objc func dimingViewClick(_ sender: UITapGestureRecognizer) {
        self.presentedViewController.dismiss(animated: true, completion: nil)
    }
    
    func adjustPresentedView() {
        guard let containView = containerView, let preView = presentedView else {
            return
        }
        containView.addSubview(preView)
        preView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
        }
    }
}

extension COPresentAnimtaionControllerViewController {
    @objc
    private func hideView(tap: UITapGestureRecognizer) {
        self.presentedViewController.dismiss(animated: true, completion: nil)
    }
}
